package testview.zhen.com.myapplication.service



import android.app.Person
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.os.Parcel
import android.os.RemoteCallbackList
import android.util.Log
import testview.zhen.com.myapplication.IOneAidlInterface
import testview.zhen.com.myapplication.IPersonBeanCallBack
import testview.zhen.com.myapplication.PersonBean
import java.lang.RuntimeException

/**
 * Create by ldr
 * on 2019/11/5 15:46.
 */
class AidlService :Service(){
    companion object{
        val TAG = "AidlService"
    }
    override fun onBind(intent: Intent?): IBinder? {
        return binder
    }

    //这个适用于回调的使用的
    var remoteCallbackList =  RemoteCallbackList<IPersonBeanCallBack>()
    private val binder = object: IOneAidlInterface.Stub() {

        override fun registerCallback(callback: IPersonBeanCallBack?) {
            remoteCallbackList.register(callback)
            Log.i(TAG,"服务端注册回调")
        }

        override fun unregisterCallback(callback: IPersonBeanCallBack?) {
            remoteCallbackList.unregister(callback)
            Log.i(TAG,"服务端取消回调")
        }

        override fun basis(anInt: Int, aLong: Long, aBoolean: Boolean, aFloat: Float, aDouble: Double, aString: String?) {
                Log.i(TAG,"得到客户端传入的数据anInt=${anInt},aLong=${aLong}" +
                        "aBoolean=${aBoolean} , aFloat=${aFloat}, aDouble=${aDouble}, aString=${aString}")
        }

        override fun getPerson(): PersonBean {
            return  PersonBean().also {
                    it.name = "小明"
                    it.age = 18
            }

        }
        //设置人名的时候回调一下通知给客户端
        override fun setPerson(a: PersonBean?) {
           Log.i(TAG,"得到客户端传入的实体Bean信息名字=${a!!.name},岁数=${a!!.age}")
            //从remoteCallbackList获取回调的对象并调用回调对象中的方法
            var n =   remoteCallbackList.beginBroadcast()
            for (i in 0 until n){
                remoteCallbackList.getBroadcastItem(i).getName(a!!.name)
                remoteCallbackList.getBroadcastItem(i).getAge(a!!.age!!)
            }
//            remoteCallbackList.finishBroadcast()
        }
            //这里用于捕获里面出现的异常
        override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
            try{
                return  super.onTransact(code, data, reply, flags)
            }catch (e:RuntimeException){
                Log.w(TAG, "Unexpected remote exception", e)
                throw e
            }
        }

    }

}